package cascade.controller.pages.commands
{
	
	import cascade.App;
	import cascade.model.Page;
	import cascade.view.pages.NewPageDialog;
	
	import flight.commands.AsyncCommand;
	import flight.net.RemoteService;
	
	import mx.rpc.Fault;

	public class CommandCreateSite extends AsyncCommand
	{
		
		public override function execute():*
		{
			var newPageDialog:NewPageDialog = new NewPageDialog();
			newPageDialog.parentPage = Cascade.view.selectedPage;
			newPageDialog.callback = onDialogSubmit;
			newPageDialog.open();
		}
		
		protected function onDialogSubmit(dialog:NewPageDialog):void
		{
			Cascade.busy.addBusy(this);
			
			if (Cascade.model.siteTree.length)
			{
				var lastSite:Page = Cascade.model.siteTree.getItemAt(Cascade.model.siteTree.length - 1) as Page;
				Cascade.service.SiteService.createSite(dialog.pageName, dialog.pageTitle, lastSite.id, result, fault);
			}
			else
				Cascade.service.SiteService.createSite(dialog.pageName, dialog.pageTitle, result, fault);
		}
		
		protected function result(page:Page):void
		{
			Cascade.model.pages.addItem(page);
			Cascade.model.siteTree.addItem(page);
			
			Cascade.busy.removeBusy(this);
			
			dispatchExecutionComplete();
		}
		
		protected function fault(info:Object):void
		{
			trace(info);
			
			Cascade.busy.removeBusy(this);
		}
	}
}